import { _decorator, Component, BoxCollider, ITriggerEvent } from 'cc';
import { BulletPropType } from '../framework/Enum';
import { GameManager } from '../framework/GameManager';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;

@ccclass('BulletProp')
export class BulletProp extends Component {
    // 移动速度,x移动速度
    private _propSpeed = 0.3
    private _propXSpeed = 0.3
    // 游戏管理节点
    private _gameManager: GameManager = null

    onEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 监听碰撞事件
        collider.on('onTriggerEnter', this._onTriggerEnter, this)
    }

    onDisEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 取消监听碰撞事件
        collider.off('onTriggerEnter', this._onTriggerEnter, this)
    }

    start() {

    }

    update(deltaTime: number) {
        const pos = this.node.position
        // 设置x轴运动方向
        if (pos.x <= -15 || pos.x >= 15) {
            this._propXSpeed = - this._propXSpeed
        }
        // 移动
        this.node.setPosition(pos.x + deltaTime * this._propXSpeed, pos.y, pos.z + deltaTime * this._propSpeed)

        // 超出边界销毁
        if (pos.z >= 50) PoolManager.instantiate().putNode(this.node)
    }

    // 碰撞事件
    private _onTriggerEnter(e: ITriggerEvent) {
        // 获取当前子弹类型名称
        const name = e.selfCollider.node.name
        
        if ( name === 'BulletH') {
            // H型子弹
            this._gameManager.changeBulletType(BulletPropType.BULLET_H)
        } else if (name === 'BulletS') {
            // S型子弹
            this._gameManager.changeBulletType(BulletPropType.BULLET_S)
        } else {
            // M型子弹
            this._gameManager.changeBulletType(BulletPropType.BULLET_M)
        }
        PoolManager.instantiate().putNode(this.node)
    }

    // 设置速度
    public setPropSpeed(gameManager: GameManager, x: number, z: number) {
        this._gameManager = gameManager
        this._propXSpeed = x
        this._propSpeed = z
    }
}

